package com.bjpowernode.controllers;

import com.bjpowernode.entities.TPermission;
import com.bjpowernode.entities.TUser;
import com.bjpowernode.querys.UserQuery;
import com.bjpowernode.result.Result;
import com.bjpowernode.services.PermissionService;
import com.bjpowernode.services.UserService;
import com.bjpowernode.utils.LoginInfoUtil;
import jakarta.annotation.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
public class UserController {
    @Resource
    private final UserService userService;
    @Resource
    private PermissionService permissionService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("api/login/user")
    public Result loginUser() {
        TUser user = LoginInfoUtil.getCurrentLoginUser();
        List<TPermission> tMenuPermissionList = permissionService.getMenuPermissionList(user.getId());
        user.setTMenuPermissionList(tMenuPermissionList);
        return Result.OK(user);
    }

    @GetMapping("api/users")
    public Result getUsersByPage(Integer current) {
        return Result.OK(userService.getUsersByPage(current));
    }

    @GetMapping("api/user/{id}")
    public Result getUserById(@PathVariable(value = "id") Integer id) {
        TUser user = userService.getUserById(id);
        return Result.OK(user);
    }

    @GetMapping(value = "/api/owners")
    public Result getOwners() {
        List<TUser> tUserList = userService.getOwners();
        return Result.OK(tUserList);
    }

    @PostMapping("api/user")
    public Result addUser(UserQuery userQuery) {
        int num = userService.addUser(userQuery);
        return num > 0 ? Result.OK() : Result.FAIL();
    }

    @PutMapping("api/user")
    public Result updateUser(UserQuery userQuery) {
        int num = userService.updateUser(userQuery);
        return num >= 1 ? Result.OK() : Result.FAIL();
    }

    @DeleteMapping(value = "/api/user/{id}")
    public Result deleteUserById(@PathVariable(value = "id") Integer id) {
        int num = userService.deleteUserById(id);
        return num >= 1 ? Result.OK() : Result.FAIL();
    }

    @DeleteMapping(value = "/api/user")
    public Result batchDeleteUsersByIds(@RequestParam(value = "ids") String ids) {
        if (!StringUtils.hasText(ids))
            throw new RuntimeException("请选择要删除的用户");
        List<String> idList = Arrays.asList(ids.split(","));
        int num = userService.batchDeleteUsersByIds(idList);
        return num >= idList.size() ? Result.OK() : Result.FAIL();
    }
}
